package com.sssre.business.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.sssre.business.exception.ServiceValidException;
import com.sssre.common.utils.StringUtils;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sssre.business.mapper.BusBpmnInfoMapper;
import com.sssre.business.domain.BusBpmnInfo;
import com.sssre.business.service.IBusBpmnInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 流程定义明细Service业务层处理
 * 
 * @author 浪兎兎
 * @date 2025-05-08
 */
@Service
public class BusBpmnInfoServiceImpl implements IBusBpmnInfoService 
{
    @Autowired
    private BusBpmnInfoMapper busBpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;


    /**
     * 查询流程定义明细
     * 
     * @param id 流程定义明细主键
     * @return 流程定义明细
     */
    @Override
    public BusBpmnInfo selectBusBpmnInfoById(Long id)
    {
        return busBpmnInfoMapper.selectBusBpmnInfoById(id);
    }

    /**
     * 查询流程定义明细列表
     * 
     * @param busBpmnInfo 流程定义明细
     * @return 流程定义明细
     */
    @Override
    public List<BusBpmnInfo> selectBusBpmnInfoList(BusBpmnInfo busBpmnInfo)
    {
        return busBpmnInfoMapper.selectBusBpmnInfoList(busBpmnInfo);
    }

    /**
     * 新增流程定义明细
     * 
     * @param busBpmnInfo 流程定义明细
     * @return 结果
     */
    @Override
    public int insertBusBpmnInfo(BusBpmnInfo busBpmnInfo)
    {
        return busBpmnInfoMapper.insertBusBpmnInfo(busBpmnInfo);
    }

    /**
     * 修改流程定义明细
     * 
     * @param busBpmnInfo 流程定义明细
     * @return 结果
     */
    @Override
    public int updateBusBpmnInfo(BusBpmnInfo busBpmnInfo)
    {
        return busBpmnInfoMapper.updateBusBpmnInfo(busBpmnInfo);
    }

    /**
     * 批量删除流程定义明细
     * 
     * @param ids 需要删除的流程定义明细主键
     * @return 结果
     */
    @Override
    public int deleteBusBpmnInfoByIds(Long[] ids)
    {
        return busBpmnInfoMapper.deleteBusBpmnInfoByIds(ids);
    }

    /**
     * 删除流程定义明细信息
     * 
     * @param id 流程定义明细主键
     * @return 结果
     */
    @Override
    public int deleteBusBpmnInfoById(Long id)
    {
        return busBpmnInfoMapper.deleteBusBpmnInfoById(id);
    }

    /**
     * 文件上传
     * @param file 文件
     * @param info 备注
     * @param bpmnType 流程类型
     * @param bpmnLabel 流程名
     * @return 结果
     */
    @Override
    @Transactional
    public int deploy(MultipartFile file, String info, Integer bpmnType, String bpmnLabel) throws IOException {
        // 数据安全性校验
        if (file == null || StringUtils.isEmpty(info) || bpmnType == null || StringUtils.isEmpty(bpmnLabel)) {
            throw new ServiceValidException("数据不能为空");
        }
        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        if (!("xml".equalsIgnoreCase(extension) || "bpmn".equalsIgnoreCase(extension))) {
            throw new ServiceValidException("上传文件必须为 xml 或 bpmn");
        }
        // 部署流程定义
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(bpmnLabel, file.getInputStream())
                .deploy();
        // 根据流程定义对象获取 key 和 version
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        String key = processDefinition.getKey();
        int version = processDefinition.getVersion();
        // 根据部署对象获取部署时间
        Date deploymentTime = deploy.getDeploymentTime();
        // 将数据插入数据库
        BusBpmnInfo busBpmnInfo = new BusBpmnInfo();
        busBpmnInfo.setBpmnLabel(bpmnLabel);
        busBpmnInfo.setBpmnType(bpmnType);
        busBpmnInfo.setProcessDefinitionKey(key);
        busBpmnInfo.setDeployTime(deploymentTime);
        busBpmnInfo.setVersion(version);
        busBpmnInfo.setInfo(info);
        return busBpmnInfoMapper.insertBusBpmnInfo(busBpmnInfo);
    }

    /**
     * 获取文件
     * @param id 主键
     * @param type 类型
     * @return 结果
     */
    @Override
    public InputStream readResource(Long id, String type) {
        // 数据安全性校验
        if (id == null || StringUtils.isEmpty(type)) {
            throw new ServiceValidException("数据不能为空");
        }
        // 查询原始对象
        BusBpmnInfo busBpmnInfo = busBpmnInfoMapper.selectBusBpmnInfoById(id);
        // 判断是否为空
        if (busBpmnInfo == null) {
            throw new ServiceValidException("流程定义不存在");
        }
        // 获取 key 查询流程定义对象
        String processDefinitionKey = busBpmnInfo.getProcessDefinitionKey();
        Integer version = busBpmnInfo.getVersion();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(processDefinitionKey)
                .processDefinitionVersion(version)
                .singleResult();
        // 如果是 xml 获取文件流
        if ("xml".equalsIgnoreCase(type)) {
            return repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getResourceName());
        } else if ("png".equalsIgnoreCase(type)) {
            // 如果是图片，则使用插件转换
            DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            return processDiagramGenerator.generateDiagram(bpmnModel,
                    Collections.emptyList(),
                    Collections.emptyList(),
                    "宋体",
                    "宋体",
                    "宋体");
        } else {
            throw new ServiceValidException("非法参数");
        }
    }

    /**
     * 撤销流程定义
     * @param id 主键
     * @return 结果
     */
    @Override
    public int cancel(Long id) {
        // 参数合法性校验
        if (id == null) {
            throw new ServiceValidException("数据不能为空");
        }
        BusBpmnInfo busBpmnInfo = busBpmnInfoMapper.selectBusBpmnInfoById(id);
        if (busBpmnInfo == null) {
            throw new ServiceValidException("数据不能为空");
        }
        // 删除数据
        busBpmnInfoMapper.deleteBusBpmnInfoById(id);
        // 删除act流程定义
        String processDefinitionKey = busBpmnInfo.getProcessDefinitionKey();
        Integer version = busBpmnInfo.getVersion();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(processDefinitionKey)
                .processDefinitionVersion(version)
                .singleResult();
        repositoryService.deleteDeployment(processDefinition.getDeploymentId(), true);
        return 1;
    }

    /**
     * 根据类型查询流程定义
     * @param flowAuditType 类型
     * @return 结果
     */
    @Override
    public BusBpmnInfo selectBusBpmnInfoByType(Integer flowAuditType) {
        return busBpmnInfoMapper.selectBusBpmnInfoByType(flowAuditType);
    }
}
